<?php

namespace App\Http\Controllers;

use App\Exports\BalancesExport;
use App\Exports\ReportExport;
use App\Models\Balance;
use App\Models\Buy;
use App\Models\Sell;
use Illuminate\Http\Request;

class BalanceController extends Controller
{
  public function indexForAdmin(Request $request)
  {
    $page = Balance::with('user:id,username,role', 'sell')
      ->when($request->has('user_username'), function ($q) use ($request) {
        $q->whereHas('user', function ($q) use ($request) {
          $q->where('username', $request->user_username);
        });
      })
      ->when($request->has('role'), function ($q) use ($request) {
        $q->whereHas('user', function ($q) use ($request) {
          $q->where('role', $request->role);
        });
      })
      ->when($request->has('type'), function ($q) use ($request) {
        $q->where('type', $request->type);
      })
      ->orderBy('id', 'desc')
      ->page();

    return success($page);
  }

  public function indexForSeller(Request $request)
  {
    $page = Balance::with('user')
      ->when($request->has('type'), function ($q) use ($request) {
        $q->where('type', $request->type);
      })
      ->when($request->has('created_at'), function ($q) use ($request) {
        $range = getRange($request->created_at);
        $q->whereBetween('created_at', $range);
      })
      ->where('user_id', sellerId())
      ->orderBy('id', 'desc')
      ->page();

    return success($page);
  }

  public function reportForSeller(Request $request)
  {
    $buys = Buy::where('seller_id', sellerId())
      ->thisMonth()
      ->latest()
      ->get();
    $sells = Sell::where('seller_id', sellerId())
      ->thisMonth()
      ->latest()
      ->get();

    $group = $buys->merge($sells)->groupBy(function ($item) {
      return $item->updated_at->format('Y-m-d');
    });

    $list = [];
    foreach ($group as $key => $rows) {
      $buy = 0;
      $sell = 0;
      $fee = 0;
      $tip = 0;
      $done_count = 0;
      $undone_count = 0;
      $done_coins = 0;
      $undone_coins = 0;

      foreach ($rows as  $row) {
        if ($row instanceof Buy) { // buy
          // if ($row->state === 'unfreeze') {
          $buy -= $row->coins;
          // }
          $fee = 1 * bcadd($fee, $row->seller_fee, 3);
          $tip = 1 * bcadd($tip, $row->seller_tip, 3);

          if ($row->state === 'unfreeze' || $row->state === 'fail') {
            $done_count++;
            $done_coins += $row->coins;
          } else {
            $undone_count++;
            $undone_coins += $row->coins;
          }
        } else {
          $sell += $row->coins;
        }
        // if (in_array($row->state, ['took', 'waiting'])) {
        //   $undone_count++;
        //   $undone_coins += $row->coins;
        // } else {
        //   $done_count++;
        //   $done_coins += $row->coins;
        // }
      }
      $list[] = [
        'date' => $key,
        'buy' => $buy,
        'sell' => $sell,
        'fee' => $fee,
        'tip' => $tip,
        'done_count' => $done_count,
        'undone_count' => $undone_count,
        'done_coins' => $done_coins,
        'undone_coins' => $undone_coins,
      ];
    }
    return success([
      'list' => $list,
      'total' => count($list)
    ]);
  }

  public function export()
  {
    $this->authCheck();
    return \Excel::download(new BalancesExport, 'balances.xlsx');
  }

  protected function authCheck()
  {
    auth()->parseToken(request('token'));
    if (auth()->guest() || auth()->user()->role !== 'seller') {
      forbidden();
    }
  }

  public function exportReport()
  {
    $this->authCheck();
    return \Excel::download(new ReportExport, 'report.xlsx');
  }

  public function update(Request $request, Balance $balance)
  {
    //
  }

  public function destroy(Balance $balance)
  {
    //
  }
}
